package com.party.admin.biz.cDataAnalysis;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.party.admin.biz.activity.MemberActBizService;
import com.party.admin.biz.system.MemberGroupBizService;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.commune.CDataAnalysisBase;
import com.party.core.model.commune.CDataAnalysisCount;
import com.party.core.model.commune.CDataAnalysisDetail;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.system.SysConfig;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.commune.ICDataAnalysisCountService;
import com.party.core.service.commune.ICDataAnalysisDetailService;
import com.party.core.service.commune.ICIntegralTypeService;
import com.party.core.service.commune.ICUserIntegralService;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.utils.MyBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CDataAnalysisBizService {
    private static Logger logger = LoggerFactory.getLogger(CDataAnalysisBizService.class);
    @Autowired
    private ICDataAnalysisCountService icDataAnalysisCountService;
    @Autowired
    private ICDataAnalysisDetailService icDataAnalysisDetailService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private MemberActBizService memberActBizService;
    @Autowired
    private IGatherFormInfoService gatherFormInfoService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ICUserIntegralService cUserIntegralService;
    @Autowired
    private ICIntegralTypeService integralTypeService;
    @Autowired
    private ISysConfigService sysConfigService;

    //总的
    public void countCDataAnalysisCount(){
        try {
            MemberGroup xingZheGongSheMemberGroup = memberGroupBizService.getXingZheGongSheMemberGroup();

            /*--------------------行知公社------------------*/
            List<String> xzgs_list = memberGroupService.getChildWithMy(xingZheGongSheMemberGroup.getId());
            //CDataAnalysisBase公共字段统计
            CDataAnalysisBase xzgs_cDataAnalysisBase = this.getCDataAnalysis(xzgs_list, null);
            CDataAnalysisCount cDataAnalysisCount_save = CDataAnalysisCount.transform(xzgs_cDataAnalysisBase);
            //cDataAnalysisCount特有字段统计
            this.getCDataAnalysisCount(xzgs_list, cDataAnalysisCount_save);
            //保存
            this.saveCDataAnalysisCount(cDataAnalysisCount_save, xingZheGongSheMemberGroup.getId());


            /*--------------------分社------------------*/
            List<String> fs_list = memberGroupService.getChild(xingZheGongSheMemberGroup.getId());
            for (String mgId : fs_list) {
                ArrayList<String> memberGroupIds = Lists.newArrayList();
                memberGroupIds.add(mgId);
                CDataAnalysisBase fs_cDataAnalysisBase = this.getCDataAnalysis(memberGroupIds, null);
                CDataAnalysisCount fs_cDataAnalysisBase_save = CDataAnalysisCount.transform(fs_cDataAnalysisBase);
                this.getCDataAnalysisCount(memberGroupIds, fs_cDataAnalysisBase_save);
                this.saveCDataAnalysisCount(fs_cDataAnalysisBase_save, mgId);
            }
        }catch (Exception e){
            logger.error("社群数据分析-总的,统计异常", e.getMessage());
        }
    }

    //每一天
    public void countCDataAnalysisDetail(List<Date> dateStrs) {
        try {
            if (dateStrs.size() > 0) {
                for (Date date : dateStrs) {
                    String s = DateUtils.formatDate(date);
                    String dateStr = s;

                    MemberGroup xingZheGongSheMemberGroup = memberGroupBizService.getXingZheGongSheMemberGroup();
                    //行知公社
                    List<String> xzgs_list = memberGroupService.getChildWithMy(xingZheGongSheMemberGroup.getId());
                    CDataAnalysisBase xzgs_cDataAnalysisBase = this.getCDataAnalysis(xzgs_list, dateStr);

                    CDataAnalysisDetail xzgs_cDataAnalysisBase_save = CDataAnalysisDetail.transform(xzgs_cDataAnalysisBase);
                    this.saveCDataAnalysisDetail(xzgs_cDataAnalysisBase_save, xingZheGongSheMemberGroup.getId(),date);

                    //分社
                    List<String> fs_list = memberGroupService.getChild(xingZheGongSheMemberGroup.getId());
                    for (String mgId : fs_list) {
                        ArrayList<String> memberGroupIds = Lists.newArrayList();
                        memberGroupIds.add(mgId);
                        CDataAnalysisBase fs_cDataAnalysisBase = this.getCDataAnalysis(memberGroupIds, dateStr);

                        CDataAnalysisDetail fs_cDataAnalysisDetail_save = CDataAnalysisDetail.transform(fs_cDataAnalysisBase);
                        this.saveCDataAnalysisDetail(fs_cDataAnalysisDetail_save, mgId,date);
                    }
                }
            } else {
                Date date = DateUtils.today();
                String dateStr = DateUtils.formatDate(date);

                MemberGroup xingZheGongSheMemberGroup = memberGroupBizService.getXingZheGongSheMemberGroup();
                //行知公社
                List<String> xzgs_list = memberGroupService.getChildWithMy(xingZheGongSheMemberGroup.getId());
                CDataAnalysisBase xzgs_cDataAnalysisBase = this.getCDataAnalysis(xzgs_list, dateStr);

                CDataAnalysisDetail xzgs_cDataAnalysisBase_save = CDataAnalysisDetail.transform(xzgs_cDataAnalysisBase);
                this.saveCDataAnalysisDetail(xzgs_cDataAnalysisBase_save, xingZheGongSheMemberGroup.getId(),null);

                //分社
                List<String> fs_list = memberGroupService.getChild(xingZheGongSheMemberGroup.getId());
                for (String mgId : fs_list) {
                    ArrayList<String> memberGroupIds = Lists.newArrayList();
                    memberGroupIds.add(mgId);
                    CDataAnalysisBase fs_cDataAnalysisBase = this.getCDataAnalysis(memberGroupIds, dateStr);

                    CDataAnalysisDetail fs_cDataAnalysisDetail_save = CDataAnalysisDetail.transform(fs_cDataAnalysisBase);
                    this.saveCDataAnalysisDetail(fs_cDataAnalysisDetail_save, mgId,null);
                }
            }
        }catch (Exception e){
            logger.error("社群数据分析-day,统计异常", e.getMessage());
        }
    }


    public void saveCDataAnalysisDetail(CDataAnalysisDetail cDataAnalysisDetail_val, String memberGroupId, Date date) throws Exception {
        if (date == null) {
            date = DateUtils.today();
        }
        String dateStr = DateUtils.formatDate(date);
        HashMap<String, Object> params = Maps.newHashMap();
        params.put("startDate", dateStr);
        params.put("endDate", dateStr);

        CDataAnalysisDetail cDataAnalysisDetail = icDataAnalysisDetailService.getCDataAnalysisDetailByMemberGroupId(memberGroupId, params);
        if (null == cDataAnalysisDetail) {
            cDataAnalysisDetail_val.setCreateDate(date);
            cDataAnalysisDetail_val.setUpdateDate(date);
            cDataAnalysisDetail_val.setMemberGroupId(memberGroupId);
            icDataAnalysisDetailService.insert(cDataAnalysisDetail_val);
        } else {
            MyBeanUtils.copyBeanNotNull2Bean(cDataAnalysisDetail_val, cDataAnalysisDetail);
            icDataAnalysisDetailService.update(cDataAnalysisDetail);
        }
    }

    public void saveCDataAnalysisCount(CDataAnalysisCount cDataAnalysisCount_save, String memberGroupId) throws Exception {
        CDataAnalysisCount cDataAnalysisCount = icDataAnalysisCountService.getCDataAnalysisCountByMemberGroupId(memberGroupId);
        if (null == cDataAnalysisCount) {
            cDataAnalysisCount_save.setMemberGroupId(memberGroupId);
            icDataAnalysisCountService.insert(cDataAnalysisCount_save);
        } else {
            MyBeanUtils.copyBeanNotNull2Bean(cDataAnalysisCount_save, cDataAnalysisCount);
            icDataAnalysisCountService.update(cDataAnalysisCount);
        }
    }

    public CDataAnalysisBase getCDataAnalysis(List<String> memberGroupIds, String dateTime) {
        HashMap<String, Object> params = Maps.newHashMap();
        params.put("startDate", dateTime);
        params.put("endDate", dateTime);

        //社群总人数（包括有手机号和没手机号的）
        params.put("isThereMobile", false);
        params.put("isThereIndustry", false);
        Integer memberTotal = 0;
        try {
            memberTotal = partnerMemberService.cAnalysisGetMemberCount(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("社群总人数统计异常", e.getMessage());
        }

        //有效会员（有绑定手机号的）
        params.put("isThereMobile", true);
        params.put("isThereIndustry", false);
        Integer effectiveMemberNum = 0;
        try {
            effectiveMemberNum = partnerMemberService.cAnalysisGetMemberCount(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("有效会员统计异常", e.getMessage());
        }

        //活跃数（参加过活动）
        params.put("isThereJob", false);
        Integer activeMemberNum = 0;
        try {
            activeMemberNum = memberActBizService.getSigninMemberCountByMemberGroupId(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("活跃数统计异常", e.getMessage());
        }

        //自组织活跃数（有社团职务的活跃人数）
        params.put("isThereJob", true);
        Integer jobActiveMemberNum = 0;
        try {
            jobActiveMemberNum = memberActBizService.getSigninMemberCountByMemberGroupId(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("自组织活跃数统计异常", e.getMessage());
        }

        //推荐会员数（有推荐过他人加入社群的）
        Integer recommendMemberNum = 0;
        try {
            recommendMemberNum = partnerMemberService.getMemberRecommendCount(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("推荐会员数统计异常", e.getMessage());
        }

        //行业数（会员分布的行业）
        params.put("isThereMobile", false);
        params.put("isThereIndustry", true);
        Integer industryNum = 0;
        try {
            industryNum = partnerMemberService.cAnalysisGetMemberCount(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("行业数统计异常", e.getMessage());
        }

        //总规模（资金）
        Map<String, String> moneyTotal_val = this.getCustomFormVal("moneyTotal");
        params.put("projectId", moneyTotal_val.get("projectId"));
        params.put("fieldId", moneyTotal_val.get("fieldId"));
        params.put("queryType", "moneyTotal");
        Double companyMoney = 0d;
        try {
            companyMoney = Double.parseDouble(gatherFormInfoService.getFormInfoValByMemberGroupId(memberGroupIds, params));
        } catch (Exception e) {
            logger.error("总规模（资金）统计异常", e.getMessage());
        }
        CDataAnalysisBase cDataAnalysisBase = new CDataAnalysisBase();
        cDataAnalysisBase.setMemberTotal(memberTotal);
        cDataAnalysisBase.setEffectiveMemberNum(effectiveMemberNum);
        cDataAnalysisBase.setActiveMemberNum(activeMemberNum);
        cDataAnalysisBase.setJobActiveMemberNum(jobActiveMemberNum);
        cDataAnalysisBase.setRecommendMemberNum(recommendMemberNum);
        cDataAnalysisBase.setIndustryNum(industryNum);
        cDataAnalysisBase.setCompanyMoney(companyMoney);
        return cDataAnalysisBase;
    }

    public void getCDataAnalysisCount(List<String> memberGroupIds,CDataAnalysisCount cDataAnalysisCount_val) {
        HashMap<String, Object> params = Maps.newHashMap();

        //发布活动次数
        Integer pubActivityNum = 0;
        try {
            pubActivityNum = activityService.getActNumByMemberGroupId(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("发布活动次数统计异常", e.getMessage());
        }

        //公益积分
        Double commonwealScore = 0d;
        try {
            params.put("typeId", integralTypeService.getIntegralTypeByName("公益").getId());
            commonwealScore = cUserIntegralService.getMemberGroupScoreByTypeId(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("公益积分统计异常", e.getMessage());
        }

        //奉献积分
        Double dedicationScore = 0d;
        try {
            params.put("typeId", integralTypeService.getIntegralTypeByName("奉献").getId());
            dedicationScore = cUserIntegralService.getMemberGroupScoreByTypeId(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("奉献积分统计异常", e.getMessage());
        }

        //学习积分
        Double studyScore = 0d;
        try {
            params.put("typeId", integralTypeService.getIntegralTypeByName("学习").getId());
            studyScore = cUserIntegralService.getMemberGroupScoreByTypeId(memberGroupIds, params);
        } catch (Exception e) {
            logger.error("学习积分统计异常", e.getMessage());
        }

        //拜访次数
        Map<String, String> visitNum_val = this.getCustomFormVal("visitNum");
        params.put("projectId", visitNum_val.get("projectId"));
        params.put("fieldId", visitNum_val.get("fieldId"));
        params.put("queryType", "visitNum");
        Integer visitNum = 0;
        try {
            visitNum = Integer.parseInt(gatherFormInfoService.getFormInfoValByMemberGroupId(memberGroupIds, params));
        } catch (Exception e) {
            logger.error("拜访次数统计异常", e.getMessage());
        }

        //参加戈壁活动次数
        Map<String, String> gobiActNum_val = this.getCustomFormVal("gobiActNum");
        params.put("projectId", gobiActNum_val.get("projectId"));
        params.put("fieldId", gobiActNum_val.get("fieldId"));
        params.put("queryType", "gobiActNum");
        Integer gobiActNum = 0;
        try {
            gobiActNum = Integer.parseInt(gatherFormInfoService.getFormInfoValByMemberGroupId(memberGroupIds, params));
        } catch (Exception e) {
            logger.error("参加戈壁活动次数统计异常", e.getMessage());
        }

        //有宗教信仰的人统计
        Map<String, String> religionCount_val = this.getCustomFormVal("religionCount");
        params.put("projectId", religionCount_val.get("projectId"));
        params.put("fieldId", religionCount_val.get("fieldId"));
        params.put("queryType", "religionCount");
        Integer religionCount = 0;
        try {
            religionCount = Integer.parseInt(gatherFormInfoService.getFormInfoValByMemberGroupId(memberGroupIds, params));
        } catch (Exception e) {
            logger.error("有宗教信仰的人统计异常", e.getMessage());
        }

        //运动时长
        Map<String, String> exerciseDuration_val = this.getCustomFormVal("exerciseDuration");
        params.put("projectId", exerciseDuration_val.get("projectId"));
        params.put("fieldId", exerciseDuration_val.get("fieldId"));
        params.put("queryType", "exerciseDuration");
        Integer exerciseDuration = 0;
        try {
            exerciseDuration = Integer.parseInt(gatherFormInfoService.getFormInfoValByMemberGroupId(memberGroupIds, params));
        } catch (Exception e) {
            logger.error("运动时长统计异常", e.getMessage());
        }

        //平均年龄
        Map<String, String> avgAgeNum_val = this.getCustomFormVal("avgAgeNum");
        Double avgAgeNum = 0.00d;
        params.put("projectId", avgAgeNum_val.get("projectId"));
        params.put("fieldId", avgAgeNum_val.get("fieldId"));
        params.put("queryType", "avgAgeNum");
        try {
            avgAgeNum = Double.parseDouble(gatherFormInfoService.getFormInfoValByMemberGroupId(memberGroupIds, params));
        }catch (Exception e){
            logger.error("平均年龄统计异常", e.getMessage());
        }
        cDataAnalysisCount_val.setAvgAgeNum(avgAgeNum);
        cDataAnalysisCount_val.setExerciseDuration(exerciseDuration);
        cDataAnalysisCount_val.setReligionCount(religionCount);
        cDataAnalysisCount_val.setGobiActNum(gobiActNum);
        cDataAnalysisCount_val.setVisitNum(visitNum);
        cDataAnalysisCount_val.setStudyScore(studyScore);
        cDataAnalysisCount_val.setDedicationScore(dedicationScore);
        cDataAnalysisCount_val.setCommonwealScore(commonwealScore);
        cDataAnalysisCount_val.setPubActivityNum(pubActivityNum);
    }

    public Map<String,String> getCustomFormVal(String code){
        SysConfig xzgsConfig = sysConfigService.findByCode("CUSTOM_FORM_VAL");
        if (xzgsConfig == null || StringUtils.isEmpty(xzgsConfig.getValue())) {
            return null;
        }
        Map<String, Object> responseMap = (Map<String, Object>) JSONObject.parse(xzgsConfig.getValue());

        Map<String,String> formVal = (Map<String,String>)responseMap.get(code);
        return formVal;
    }
}
